package com.example.video.util.scheduled;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Service
public class DynamicTaskScheduler {

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    private final Map<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();

    public String scheduleTask(String taskId, Runnable task, LocalDateTime startTime) {
        String result = "";
        if (tasks.containsKey(taskId)) {
            cancelTask(taskId);
            result = "更新任务成功！";
        }else{
            result = "添加任务成功！";
        }
        long initialDelay = computeInitialDelay(startTime);
        long period = TimeUnit.DAYS.toMillis(1);

        ScheduledFuture<?> scheduledTask = scheduledExecutorService.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS);
        tasks.put(taskId, scheduledTask);

        return result;
    }

    public void cancelTask(String taskId) {
        ScheduledFuture<?> scheduledTask = tasks.remove(taskId);
        if (scheduledTask != null) {
            scheduledTask.cancel(false);
        }
    }

    public String getAllTaskIds(){
        StringBuilder status = new StringBuilder("当前任务列表：\n");
        tasks.forEach((taskId, future) -> {
            status.append("任务ID: ").append(taskId).append(", 状态: ").append(future.isCancelled() ? "已取消" : "运行中").append("\n");
        });
        return status.toString();

    }


    private long computeInitialDelay(LocalDateTime startTime) {
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(startTime)) {
            startTime = startTime.plusDays(1);
        }
        return Duration.between(now, startTime).toMillis();
    }
}
